package com.wcfsy.wechat.wx.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wcfsy.wechat.wx.client.Client;
import com.wcfsy.wechat.wx.entity.Coupon;
import com.wcfsy.wechat.wx.entity.KcFlow;
import com.wcfsy.wechat.wx.entity.Member;
import com.wcfsy.wechat.wx.entity.PaymentFlow;
import com.wcfsy.wechat.wx.entity.Product;
import com.wcfsy.wechat.wx.entity.ProductType;
import com.wcfsy.wechat.wx.entity.TemplateData;
import com.wcfsy.wechat.wx.entity.WechatUserInfo;
import com.wcfsy.wechat.wx.service.RegisteredService;
import com.wcfsy.wechat.wx.service.WeChatQrCodeService;
import com.wcfsy.wechat.wx.sys.dao.CouponDao;
import com.wcfsy.wechat.wx.sys.dao.MemberDao;
import com.wcfsy.wechat.wx.sys.dao.PaymentFlowDao;
import com.wcfsy.wechat.wx.sys.dao.ProductConfigDao;
import com.wcfsy.wechat.wx.sys.dao.ProductTypeDao;
import com.wcfsy.wechat.wx.util.Constant;
import com.wcfsy.wechat.wx.util.DateStyle;
import com.wcfsy.wechat.wx.util.DateUtil;
import com.wcfsy.wechat.wx.util.JsonMessage;
import com.wcfsy.wechat.wx.util.MD5;
import com.wcfsy.wechat.wx.util.PushMessage;
import com.wcfsy.wechat.wx.util.StringUtil;
import com.wcfsy.wechat.wx.util.WechatPayment;
import com.wcfsy.wechat.wx.util.WechatUtil;
import com.wcfsy.wechat.wx.util.ehcache.EHCacheConfig;
import com.wcfsy.wechat.wx.util.ehcache.EHCacheUtil;

@Controller
@RequestMapping("/register/")
public class RegisteredController extends BaseController{

	private  Logger logger = LoggerFactory.getLogger(this.getClass());
	
	
	@Resource
	private RegisteredService registeredService;
	
	
	@Resource
	private WechatUtil wechatUtil;
	
	@Resource
	private WeChatQrCodeService weChatQrCodeService;
	
	@Resource
	private MemberDao memberDao;
	
	@Resource
	private PaymentFlowDao paymentFlowDao;
	
	@Resource
	private ProductConfigDao productConfigDao;
	
	@Resource
	private CouponDao couponDao;
	
	@Resource
	private ProductTypeDao productTypeDao;
	
	@Resource
	private PushMessage pushMessage;
	/**
	 *  获取微信用户信息
	 * @param mobile
	 * @param pwd
	 * @param code
	 * @return
	 */
	@RequestMapping(value="getWechat",produces = { "application/json;charset=UTF-8" })
	@ResponseBody
	public JsonMessage getWechat(String code){
		try {
			if(StringUtils.isEmpty(code)){
				return JsonMessage.getErrorJson("code 不能为空");	
			}
			com.wcfsy.wechat.wx.util.WechatUtil.WechatResp resp = wechatUtil.wechatAccessToken(code);
			logger.info("wechatAccessToken is resp = " + JSON.toJSONString(resp));
			if(!resp.isSuccess()){
				logger.warn("获取token失败 : " + resp.toString());
			}
			logger.info("WechatResp  = " + resp.toString() +"{"+resp.getString("access_token") +","+resp.getString("openid")+"}");
			com.wcfsy.wechat.wx.util.WechatUtil.WechatResp wechatResp = null;
			try {
				wechatResp = wechatUtil.wechatUserinfo(resp.getString("access_token"), resp.getString("openid"));
				logger.info("wechatUserinfo is wechatResp = " + JSON.toJSONString(resp));
			} catch (Exception e) {
				logger.warn("获取用户信息异常", e);
			}
			if(!wechatResp.isSuccess()){
				return JsonMessage.getErrorJson("获取用户信息失败");
			}
			WechatUserInfo wechatUser = new WechatUserInfo();
			wechatUser.setCreateDate(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
			wechatUser.setUnionid(wechatResp.getString("unionid"));
			wechatUser.setHeadimgurl(wechatResp.getString("headimgurl"));
			wechatUser.setOpenid(wechatResp.getString("openid"));
			wechatUser.setSex(wechatResp.getString("sex"));
			wechatUser.setNickname(StringUtil.encode(wechatResp.getString("nickname")));
			registeredService.saveWechatUserInfo(wechatUser);
			return JsonMessage.getSuccessJson(wechatResp);
		} catch (Exception e) {
			logger.error("获取微信用户信息异常", e);
			return JsonMessage.getErrorJson("网络异常");
		}
		
	}
	
	/**
	 * 获取用户接口信息错误
	 * @param id
	 * @param uid
	 * @param unionid
	 * @return
	 */
	@RequestMapping(value="getUser",produces = { "application/json;charset=UTF-8" })
	@ResponseBody
	public JsonMessage getUser(int id,@RequestParam(value="unionid",required=false)int uid,@RequestParam(value="unionid",required=false)String unionid){
		try {
			if(id <= 0){
				return JsonMessage.getErrorJson("id 参数错误");
			}
			WechatUserInfo wechatUser = new WechatUserInfo();
			if(uid > 0){
				wechatUser.setUid(uid);
			}
			if(StringUtils.isEmpty(unionid)){
				wechatUser.setUnionid(unionid);
			}
			wechatUser.setId(id);
			WechatUserInfo user = registeredService.getWechatUserInfo(wechatUser);
			if(StringUtil.isNotEmpty(user.getNickname())){
				user.setNickname(StringUtil.decode(user.getNickname()));
			}
			logger.info("用户信息: user = " + JSON.toJSONString(user));
			return JsonMessage.getSuccessJson(user);
		} catch (Exception e) {
			logger.error("获取用户信息失败" , e);
			return JsonMessage.getErrorJson("网路异常");
		}
	}
	
	
	/**
	 * 注册
	 * @param mobile
	 * @param pwd
	 * @param code
	 * @return
	 */
	@RequestMapping(value="regist",produces = { "application/json;charset=UTF-8" })
	@ResponseBody
	public JsonMessage register(HttpServletResponse response,String name,String unionid,String mobile,
			String password, String email,String headimgurl,String openid,HttpServletRequest request,String sex){
		try {
			if(StringUtils.isEmpty(mobile)){
				return JsonMessage.getErrorJson("手机号不能空");
			}else if(StringUtils.isEmpty(password)){
				return JsonMessage.getErrorJson("密码不能为空");		
			}else if(StringUtils.isEmpty(email)){
				return JsonMessage.getErrorJson("邮箱不能为空");	
			}else if(StringUtils.isEmpty(unionid)){
				return JsonMessage.getErrorJson("unionid不能为空");
			}
			WechatUserInfo wechatUserMobile = new WechatUserInfo();
			wechatUserMobile.setMobile(mobile);
			WechatUserInfo wechatUserInfo = registeredService.getWechatUserInfo(wechatUserMobile);
			if(wechatUserInfo != null){
				 logger.info("wechatUserInfo = " +JsonMessage.getErrorJson("手机号已注册"));
				 return JsonMessage.getErrorJson("手机号已注册");
			}
			
			JsonMessage jsonMessage = wcfsyBBsRegister(name,password,email);
			if(!"succeed".equals(jsonMessage.getSuccess())){
				return jsonMessage;
			}
			String uid = jsonMessage.getMessage();
			Integer id = Integer.parseInt(uid);
			
			logger.info("论坛返回信息: " + JSON.toJSONString(jsonMessage));
			WechatUserInfo wechatUser = new WechatUserInfo();
			wechatUser.setLoginPwd(MD5.encode(password, "utf-8"));
			wechatUser.setMobile(mobile);
			wechatUser.setCreateDate(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
			wechatUser.setStatus("1");
			wechatUser.setUnionid(unionid);
			wechatUser.setUid(id);
			wechatUser.setHeadimgurl(headimgurl);
			wechatUser.setOpenid(openid);
			wechatUser.setSex(sex);
			wechatUser.setEmail(email);
			wechatUser.setLoginPwd(password);
			wechatUser.setUserAs(name);
			wechatUser.setUserType("1");
			JsonMessage qrMsg = weChatQrCodeService.createQrCode("wcfsy"+uid);
			if("succeed".equals(qrMsg.getSuccess())){
				wechatUser.setQrCode(qrMsg.getMessage());
			}
			try {
				WechatUserInfo wechatUnionid = null;
				if(!StringUtils.isEmpty(unionid)){
					WechatUserInfo wechat = new WechatUserInfo();
					wechat.setUnionid(unionid);
					wechatUnionid = registeredService.getWechatUserInfo(wechatUserInfo);
				}
			
				if(wechatUnionid == null){
					registeredService.saveWechatUserInfo(wechatUser);
				}else{
					registeredService.updateWechatUserInfo(wechatUser);
				}
				
				logger.info("注册信息:wechatUser = " + wechatUser);
				EHCacheUtil.setValue(EHCacheConfig.EHCACHENAME, "session_"+id, wechatUser, 24*60*60);
				
				WechatUserInfo wechat = registeredService.getWechatUserInfo(wechatUserInfo);
				logger.info("注册成功:" + JsonMessage.getSuccessJson(wechat));
				return  JsonMessage.getSuccessJson(wechat);
			} catch (Exception e) {
				if(e.getMessage().contains("for key 'uq_user_info_phone'")){
					logger.error("插入数据错误", e);
					return JsonMessage.getErrorJson("手机号已经注册");
				}
				logger.error("插入数据错误", e);
				return JsonMessage.getErrorJson("注册失败");
			}
		} catch (Exception e) {
			logger.error("注册用户失败" , e);
			return JsonMessage.getErrorJson("网络异常");
		}
	}
	
	/**
	 * 获取用户信息
	 * @param mobile
	 * @return
	 */
	@RequestMapping(value="getWechatUserInfo",produces={"application/json;charset=UTF-8"})
	@ResponseBody
	public JsonMessage getWechatUserInfo(HttpServletRequest request,int userId){
		logger.info(" userId = " +userId);
		WechatUserInfo wechatUserInfo = new WechatUserInfo();
		wechatUserInfo.setId(userId);
		try {
			wechatUserInfo = registeredService.getWechatUserInfo(wechatUserInfo);
			wechatUserInfo.setNickname(StringUtil.decode(wechatUserInfo.getNickname()));
			logger.info("本地库查询的数据 : " + JSON.toJSONString(wechatUserInfo));
			return JsonMessage.getSuccessJson(wechatUserInfo);
		} catch (Exception e) {
			logger.error("数据查询异常 ", e);
			return JsonMessage.getErrorJson("网络异常");
		}
	}
	
	public static JsonMessage wcfsyBBsRegister(String name,String pwd,String email){
		Client uc = new Client();
//		生成同步退出的代码
		String $returns = uc.uc_user_register(name, pwd ,email);
		int $uid = Integer.parseInt($returns);
		if($uid <= 0) {
			if($uid == -1) {
				return JsonMessage.getErrorJson("用户名不合法");
			} else if($uid == -2) {
				return JsonMessage.getErrorJson("包含要允许注册的词语");
			} else if($uid == -3) {
				return JsonMessage.getErrorJson("用户名已经存在");
			} else if($uid == -4) {
				return JsonMessage.getErrorJson("Email 格式有误");
			} else if($uid == -5) {
				return JsonMessage.getErrorJson("Email 不允许注册");
			} else if($uid == -6) {
				return JsonMessage.getErrorJson("该 Email 已经被注册");
			} else {
				return JsonMessage.getErrorJson("未定义");
			}
		} else {
			return JsonMessage.getWCFSYSuccessJson($returns);
		}
	}
	
	/**
	 * 会员列表  加会员详情
	 * @return
	 */
	@RequestMapping(value="member",produces={"application/json;charset=UTF-8"})
	@ResponseBody
	public JsonMessage member(int id){
		if(id > 0){
			Member member = memberDao.getById(id);
			logger.info("会员列表 members = {0}" , JSON.toJSONString(member));
			return JsonMessage.getSuccessJson(member); 
		}
		Map<String,Object> map = new HashMap<String, Object>();
		List<Member> members;
		try {
			members = memberDao.queryMembers(map);
			logger.info("会员列表 members = {0}" , JSON.toJSONString(members));
			return JsonMessage.getSuccessJson(members);
		} catch (Exception e) {
			logger.error("查询错误 " , e);
			return JsonMessage.getErrorJson("查询失败");
		}
	}
	
	/**
	 *  获取用所有优惠券 和优惠券详情
	 * @return
	 */
	@RequestMapping(value="coupon",produces={"application/json;charset=UTF-8"})
	@ResponseBody
	public JsonMessage coupon(int id,int userId){
		if(id > 0){
			Coupon coupon = couponDao.getById(id);
			logger.info("优惠券列表 coupon = {0}" , JSON.toJSONString(coupon));
			return JsonMessage.getSuccessJson(coupon); 
		}
		if(userId <= 0){
			return JsonMessage.getErrorJson("用户ID不能为空");
		}
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("userId", userId);
		List<Coupon> coupons;
		try {
			coupons = couponDao.queryCoupons(map);
			logger.info("优惠券列表 coupons = {0}" , JSON.toJSONString(coupons));
			return JsonMessage.getSuccessJson(coupons);
		} catch (Exception e) {
			logger.error("查询错误 " , e);
			return JsonMessage.getErrorJson("查询失败");
		}
	}
	
	/**
	 *  获取用户所有订单列表， 和订单详情
	 * @return
	 */
	@RequestMapping(value="paymentFlow",produces={"application/json;charset=UTF-8"})
	@ResponseBody
	public JsonMessage paymentFlow(int id,int userId){
		if(id > 0){
			PaymentFlow paymentFlow = paymentFlowDao.getById(id);
			logger.info("订单列表 paymentFlow = {0}" , JSON.toJSONString(paymentFlow));
			return JsonMessage.getSuccessJson(paymentFlow); 
		}
		if(userId <= 0){
			return JsonMessage.getErrorJson("用户ID不能为空");
		}
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("userId", userId);
		List<PaymentFlow> paymentFlows;
		try {
			paymentFlows = paymentFlowDao.queryPaymentFlows(map);
			logger.info("订单列表 paymentFlows = {0}" , JSON.toJSONString(paymentFlows));
			return JsonMessage.getSuccessJson(paymentFlows);
		} catch (Exception e) {
			logger.error("查询错误 " , e);
			return JsonMessage.getErrorJson("查询失败");
		}
	}
	
	/**
	 *  获取产品类型
	 * @return
	 */
	@RequestMapping(value="productType",produces={"application/json;charset=UTF-8"})
	@ResponseBody
	public JsonMessage productType(){
		List<ProductType> productTypes;
		try {
			productTypes = productTypeDao.queryProductTypes();
			logger.info("产品类型列表 productTypes = {0}" , JSON.toJSONString(productTypes));
			return JsonMessage.getSuccessJson(productTypes);
		} catch (Exception e) {
			logger.error("查询错误 " , e);
			return JsonMessage.getErrorJson("查询失败");
		}
	}
	
	/**
	 *  获取产品列表
	 * @return
	 */
	@RequestMapping(value="queryProducts",produces={"application/json;charset=UTF-8"})
	@ResponseBody
	public JsonMessage queryProducts(int typeId,int id){
		if(id > 0){
			Product product = productConfigDao.getById(id);
			logger.info("会员列表 members = {0}" , JSON.toJSONString(product));
			return JsonMessage.getSuccessJson(product); 
		}
		if(typeId <= 0){
			return JsonMessage.getErrorJson("类型不能为空");
		}
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("typeId", typeId);
		List<Product> products;
		try {
			products = productConfigDao.queryProducts(map);
			logger.info("产品列表 products = {0}" , JSON.toJSONString(products));
			return JsonMessage.getSuccessJson(products);
		} catch (Exception e) {
			logger.error("查询错误 " , e);
			return JsonMessage.getErrorJson("查询失败");
		}
	}
	
	/**
	 *  获取推荐产品列表
	 * @return
	 */
	@RequestMapping(value="queryRecommendProducts",produces={"application/json;charset=UTF-8"})
	@ResponseBody
	public JsonMessage queryRecommendProducts(){
		List<Product> products;
		try {
			products = productConfigDao.queryRecommendProducts();
			logger.info("推荐产品列表 products = {0}" , JSON.toJSONString(products));
			return JsonMessage.getSuccessJson(products);
		} catch (Exception e) {
			logger.error("查询错误 " , e);
			return JsonMessage.getErrorJson("查询失败");
		}
	}
	
	
	
	
	/**
	 * 购买产品
	 * @param product
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/payInfo/purchasedProduct",produces={"application/json;charset=UTF-8"})
	@ResponseBody
	public JsonMessage purchasedProduct(int id,int uid,int userId,HttpServletRequest request){
		WechatUserInfo user = null;
		try {
			if(uid <= 0){
				return JsonMessage.getErrorJson("该用户不存在");
			}
			if(id <= 0){
				return JsonMessage.getErrorJson("产品不存在");
			}
			Product product = productConfigDao.getById(id); //获取产品详细信息
			if(product == null){
				return JsonMessage.getErrorJson("产品不存在");
			}
			Date current = new Date();
			if (1 == DateUtil.compareDate(current, DateUtil.StringToDate(product.getDepartureTime()))) {
				Product pt = new Product();
				pt.setStats(2);
				pt.setId(product.getId());
				productConfigDao.update(pt);
				return JsonMessage.getErrorJson("产品购买已经结束");
			}
			Map<String,Object> parmMap = new HashMap<String,Object>();
			parmMap.put("state", "ok");
			parmMap.put("productId", product.getId());
			int count = paymentFlowDao.count(parmMap);
			if(count > product.getMaxNumber()){
				return JsonMessage.getErrorJson("该产品购买人数已上限");
			}
			if(isLogin(product.getUid(), request)){
				 user = (WechatUserInfo)EHCacheUtil.get("session_"+product.getUid());
			}
			if(user == null){
				user = new WechatUserInfo();
				user.setUid(uid);
				user.setId(userId);
				user = registeredService.getWechatUserInfo(user);
			}
			if(user == null){
				return JsonMessage.getErrorJson("该用户不存在");
			}
			String orderNum = DateUtil.DateToString(new Date(), DateStyle.YYYYMMDDHHMMSS) + StringUtil.randomCode(4);
			EHCacheUtil.setValue(EHCacheConfig.EHCACHENAME, "session_"+user.getUid(), user, 30*24*60*60);
			ProductType productType = productTypeDao.getById(product.getTypeId());
			if(user.getMemberId() > 0){
				PaymentFlow paymentFlow = new PaymentFlow();
				//外拍免费
				if(productType.getType().contains("wcfhd5")){
					paymentFlow.setProductId(product.getId());
					paymentFlow.setState(Constant.OK);//支付
					paymentFlow.setProductName(product.getProductName());
					paymentFlow.setCreateDate(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
					paymentFlow.setMemberId(user.getMemberId());
					paymentFlow.setMemberName(user.getMemberName());
					paymentFlow.setMobile(user.getMobile());
					paymentFlow.setOrderNumber("HY"+orderNum);
					paymentFlow.setPrice(product.getPrice());
					paymentFlow.setDiscount(product.getDiscount());
					paymentFlow.setRealPrice(product.getDiscountPrice());
					paymentFlow.setUid(user.getUid());
					paymentFlow.setUserName(user.getNickname());
					paymentFlow.setUserId(user.getId());
					paymentFlowDao.add(paymentFlow);
					return JsonMessage.getSuccessJson("购买成功");
					
				}else if(user.getMemberName().equals("游拍会员") && productType.getType().contains("wcflp14")){
					paymentFlow.setProductId(product.getId());
					paymentFlow.setState(Constant.OK);//支付
					paymentFlow.setProductName(product.getProductName());
					paymentFlow.setCreateDate(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
					paymentFlow.setMemberId(user.getMemberId());
					paymentFlow.setMemberName(user.getMemberName());
					paymentFlow.setMobile(user.getMobile());
					paymentFlow.setOrderNumber("HY"+orderNum);
					paymentFlow.setPrice(product.getPrice());
					paymentFlow.setDiscount(product.getDiscount());
					paymentFlow.setRealPrice(product.getDiscountPrice());
					paymentFlow.setUid(user.getUid());
					paymentFlow.setUserName(user.getNickname());
					paymentFlow.setUserId(user.getId());
					paymentFlowDao.add(paymentFlow);
					return JsonMessage.getSuccessJson("购买成功");
				}
			}
			
			logger.info("************openid***********为："+user.getOpenid());
			//获取prepayid
			Map<String ,String> map=new HashMap<String,String>();
			String nonceStr=UUID.randomUUID().toString().substring(0, 32);
			long timestamp = System.currentTimeMillis() / 1000;
			map.put("appid", wechatUtil.appId);//微信appid
			map.put("mch_id", wechatUtil.mch_id);//商户ID
			map.put("nonce_str",nonceStr);//随机字符串
			map.put("body",  String.valueOf(product.getId()));//产品名称
			map.put("out_trade_no", orderNum);//订单号
			if(user.getMemberId() > 0){ //会员是折扣价格
				if(productType.getType().contains("wcfhy")){
					Member member = memberDao.getById(user.getMemberId());
					//产品是会员 小于自身的会员是不能购买的
					if(Integer.parseInt(productType.getType().split("wcfhy")[1]) < member.getMemberLevel()){
						return JsonMessage.getErrorJson("不能购买比自己小的会员");
					}
				}
				map.put("total_fee", String.valueOf((int)product.getDiscountPrice() * 100));//真是价格	
			}else{//不是会员是原价
				map.put("total_fee", String.valueOf((int)product.getPrice() * 100));//真是价格
			}
			map.put("spbill_create_ip",request.getRemoteAddr());
			String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/"; 
			map.put("notify_url", basePath +"/register/payInfo/info");
			map.put("trade_type", "JSAPI");
			map.put("openid", user.getOpenid());
			logger.info("支付参数: map = " + JSON.toJSONString(map));
			String paySign=WechatPayment.getPayCustomSign(map,wechatUtil.payment_key);
			map.put("sign",paySign);
			String xml=WechatPayment.ArrayToXml(map);
			String prepayid= WechatPayment.getPrepayid(xml);
			logger.info("prepareid*****************************="+prepayid);
			//封装h5页面调用参数
			Map<String ,String > signMap=new HashMap<String ,String >();
			signMap.put("appId", wechatUtil.appId);
			logger.info("appId={0},timeStamp={1},package={2},signType={3},nonceStr={4}"
					+ "appId = "+wechatUtil.appId+",timeStamp="+timestamp+"package"+prepayid+""
							+ ",signType = MD5,nonceStr = "+nonceStr);
			signMap.put("timeStamp", String.valueOf(timestamp));
			signMap.put("package", "prepay_id="+prepayid);
			signMap.put("signType", "MD5");
			signMap.put("nonceStr", nonceStr);
			JSONObject json = new JSONObject();
			json.put("paytimestamp", String.valueOf(timestamp));
			json.put("paypackage", "prepay_id="+prepayid);
			json.put("paynonceStr", nonceStr);
			json.put("paysignType", "MD5");
			String paySign2=WechatPayment.getPayCustomSign(signMap,wechatUtil.payment_key);
			json.put("paySign", paySign2);
			json.put("orderNumber", orderNum); // 订单 用户修改支付状态
			json.put("appId", wechatUtil.appId);
			logger.info("paySign="+paySign2);
			PaymentFlow paymentFlow = new PaymentFlow();
			paymentFlow.setProductId(product.getId());
			paymentFlow.setState(Constant.NOTPAID);//未支付
			paymentFlow.setProductName(product.getProductName());
			paymentFlow.setCreateDate(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
			paymentFlow.setMemberId(user.getMemberId());
			paymentFlow.setMemberName(user.getMemberName());
			paymentFlow.setMobile(user.getMobile());
			paymentFlow.setOrderNumber(orderNum);
			paymentFlow.setPrice(product.getPrice());
			paymentFlow.setDiscount(product.getDiscount());
			paymentFlow.setRealPrice(product.getDiscountPrice());
			paymentFlow.setUid(user.getUid());
			paymentFlow.setUserName(user.getNickname());
			paymentFlow.setUserId(user.getId());
			paymentFlowDao.add(paymentFlow);
			return JsonMessage.getSuccessJson(json);
		} catch (Exception e) {
			logger.error("微信支付链接错误", e);
			return JsonMessage.getErrorJson("网络错误");
		}
	}
	
	/**
	 * 处理返现 生成优惠券
	 * @param product
	 * @param wechatUserInfo
	 */
	private void cashback(Product product,WechatUserInfo wechatUserInfo){
		try {
			if(1 == product.getCashback()){
				logger.info("返现开始");
				if(wechatUserInfo.getMemberId() > 0){ // 该用户是否是会员
					final Coupon coupon = new Coupon();
					ProductType productType = productTypeDao.getById(product.getTypeId());
					WechatUserInfo user = new WechatUserInfo();
					if(productType.getType().contains("wcfhy")){
						//开通业务
						openBusiness(wechatUserInfo,productType,product);
						//被推荐人
						if(wechatUserInfo.getRecommUserId() > 0){ 
							user.setId(wechatUserInfo.getRecommUserId());
							final WechatUserInfo wechatUser = registeredService.getWechatUserInfo(user);
							if(wechatUser.getMemberId() > 0){// 当前用户一定要是会员
								Member member = memberDao.getById(wechatUser.getMemberId());
								coupon.setCreateDate(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
								coupon.setUid(wechatUser.getUid());
								coupon.setUserId(wechatUser.getId());
								coupon.setUserName(wechatUser.getNickname());
								coupon.setProductName(product.getProductName());
								coupon.setState(1);
								int price =0;
								if(member.getMemberLevel() >= 4){ // 会员等级大于等于 最高会员的 返现 0.15 否则 0.1
									price = (int) (product.getDiscountPrice() * 0.15);
								}else{
									price = (int) (product.getDiscountPrice() * 0.1);
								}
								coupon.setRemake("您推荐的手机号为"+wechatUserInfo.getMobile()+"用户开通了五次方"+productType.getName()+",因此获得一张"+price+"元优惠券。");
								coupon.setPrice(price);
								coupon.setCouponNmber(DateUtil.DateToString(new Date(), DateStyle.YYYYMMDDHHMMSS)+StringUtil.randomCode(2));
								couponDao.add(coupon);
								//推送一条微信消息
								WechatUtil.poolThreadExecutor.execute(new Runnable() {
									@Override
									public void run() {
										sendMessage(wechatUser,coupon);
									}
								});
							}
						}
					}
				}
			}
		} catch (Exception e) {
			logger.error("优惠券处理异常", e);
		}
	}

	private void sendMessage(WechatUserInfo user,Coupon coupon){
		if(!StringUtils.isEmpty(user.getOpenid())){
			Map<String,TemplateData> templateMap = new HashMap<String,TemplateData>();
			PushMessage.addTemplateData("first","恭喜您，尊敬五次方会员："+StringUtil.decode(user.getNickname())+"，获得一张"+coupon.getPrice()+"元优惠券",templateMap);
			PushMessage.addTemplateData("keyword1","五次方优惠券",templateMap);
			PushMessage.addTemplateData("keyword2",coupon.getCouponNmber(),templateMap);
			PushMessage.addTemplateData("keyword3","不限",templateMap);
			PushMessage.addTemplateData("remark","详情进入五次方公众号个人中心查看优惠券 ，解释权归五次方所有...",templateMap);
			pushMessage.sendTemplateMessage(user.getOpenid(), "H0JLPDnsiX9NB5XqR4_7FahhuF4-_sFFuv5wmuZGgig", templateMap, "http://www.wcfsy.com");
		}
	}
	
	@RequestMapping(value="/payInfo/info",produces={"application/json;charset=UTF-8"})
	@ResponseBody
	public void payInfoInfo(){
		
		logger.info("===================微信接收到支付通知======================");
	}
	
	/**
	 *  前端回调地址支付成功， 或者失败
	 * @param paymentFlow
	 * @return
	 */
	@RequestMapping(value="/payInfo/paymentCallBak",produces={"application/json;charset=UTF-8"})
	@ResponseBody
	public JsonMessage paymentCallBak(PaymentFlow paymentFlow){
		try {
			if(StringUtils.isEmpty(paymentFlow.getOrderNumber())){
				return JsonMessage.getErrorJson("OrderNumber订单号不能为空");
			}
			if(StringUtils.isEmpty(paymentFlow.getState())){
				return JsonMessage.getErrorJson("支付状态不能为空");
			}
			if(paymentFlow.getUid() <= 0){
				return JsonMessage.getErrorJson("用户不存在");
			}
			if(paymentFlow.getProductId() <= 0){
				return JsonMessage.getErrorJson("产品不存在");
			}
			paymentFlow.setUpdateDate(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
			paymentFlowDao.update(paymentFlow);
			//支付成功之后 开通业务，是活动就报名成功， 是课程就购买成功，
			//是会员就开通会员，该反优惠券反优惠券 普通会员介绍一个人10%， 尊贵会员返现15%，
			if(Constant.OK.equals(paymentFlow.getState())){
				Product product = productConfigDao.getById(paymentFlow.getProductId());
				WechatUserInfo user = (WechatUserInfo)EHCacheUtil.get("session_"+paymentFlow.getUid());
				//生成优惠券
				cashback(product,user);
			}
			return JsonMessage.getSuccessJson("更新成功");
		} catch (Exception e) {
			logger.error("更新支付状态失败 " , e);
			return JsonMessage.getErrorJson("更新支付状态失败, 网络异常");
		}
	}
	
	/**
	 * 开通业务 会员业务
	 * @param product
	 * @param wechatUserInfo
	 */
	private void openBusiness(WechatUserInfo wechatUserInfo,ProductType productType,Product product){
		KcFlow kcflow= new KcFlow();
		kcflow.setProductId(product.getId());
		kcflow.setUserId(wechatUserInfo.getId());
		kcflow.setCreateDate(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
		if(productType.getType().contains("wcfhy")){ //会员
			String type = productType.getType().split("wcfhy")[1];
			if(StringUtil.isNotEmpty(type)){
				int hy = Integer.parseInt(type);
				Member member = memberDao.queryMember(hy);
				wechatUserInfo.setMemberId(member.getId());
				wechatUserInfo.setMemberName(member.getMemberName());
				registeredService.updateWechatUserInfo(wechatUserInfo);
				if(hy == 2 || hy == 4){
					kcflow.setCourseId(hy);
				}
			}
		}else{
			List<ProductType> productTypes = productTypeDao.queryProductTypes();
			int leng = productTypes.size() > 0 ? productTypes.size() : 0;
			for (int i = 0; i <leng; i++) {
				ProductType prType = productTypes.get(i);
				String type = prType.getType().replaceAll("[0-9]","");
				if(productType.getType().contains(type)){
					cheString(productType,type,kcflow);
				}
			}
		}
		couponDao.saveKcflow(kcflow);
	}
	
	private void cheString(ProductType productType,String type,KcFlow kcflow){
		String id = productType.getType().split(type)[1];
		if(StringUtil.isNotEmpty(id)){
			int typeId = Integer.parseInt(type);
			kcflow.setCourseId(typeId);
		}
	}

	
	@RequestMapping("paymentPage")
	public String paymentPage(){
		return "payment/payment";
	}
}
